<template>
  <el-dialog
    v-model="showDialog"
    :title="title"
    width="30%"
    :userData="userData"
    draggable
  >
    <el-form label-width="80px">
      <el-form-item label="用户">
        <el-radio-group v-model="userData.role" size="large">
          <el-radio-button label="商家" />
          <el-radio-button label="管理员" />
        </el-radio-group>
      </el-form-item>
      <el-form-item label="用户名" prop="username">
        <el-input v-model="userData.username" type="text"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="userData.password" type="password" />
      </el-form-item>
      <el-form-item label="电话号码" prop="tel"
        ><el-input v-model="userData.tel" type="text" />
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="onSubmit"> 确定 </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { defineProps, defineExpose, reactive, ref, watch, defineEmits } from "vue";
import { register, userUpdate, UserList } from "@/request/api";
import { userFormData } from "@/util/data";
import { ElMessage } from "element-plus";
const prop = defineProps({
  userData: Object,
  title: String,
  page: Number,
});
const pageData = {
  page: 1,
  pageSize: 9,
};
const showDialog = ref(false);
defineExpose({ showDialog });
const userData = reactive(userFormData);

watch(
  () => prop.userData,
  (newVal: any, oldVal: any) => {
    userData.username = newVal.username;
    userData.role = newVal.role ? "管理员" : "商家";
    userData.tel = newVal.tel;
    userData.password = newVal.password;
  },
  { deep: true }
);

const emits = defineEmits(["getData"]);
const dataList = ref([]);
const count = ref(0);
const getUserList = async () => {
  const { data } = await UserList(pageData);
  dataList.value = data.res;
  count.value = data.count;
};
// 提交
const onSubmit = async () => {
  userData.role = userData.role == "商家" ? 0 : 1;
  pageData.page = prop.page;
  console.log(prop.title);

  if (prop.title === "添加用户") {
    await register(userData).then(async (res) => {
      showDialog.value = false;
      ElMessage.success("添加成功");
      await getUserList();
      emits("getData", dataList.value, count.value);
    });
  } else {
    await userUpdate({ ...userData, id: prop?.userData?.id }).then(async (res) => {
      showDialog.value = false;
      ElMessage.success("编辑成功");
      await getUserList();
      emits("getData", dataList.value, count.value);
    });
  }
};
</script>
